package com.joymart.file.rest;


import com.joymart.common.error.handling.JoymartBusinessException;
import com.joymart.common.oss.OSSService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileController {

    @Autowired
    private OSSService ossService;

    // 处理文件上传请求
    @SneakyThrows
    @PostMapping("/admin/files")
    public Object handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new JoymartBusinessException("File is empty");
        }

        String url = ossService.upload(generateUniqueFileName(file.getOriginalFilename()), file.getBytes());
        return Map.of("url", url);
    }


    @GetMapping("/files/signature")
    public Object generateSignature(@RequestParam String dir) {
        if(Arrays.asList("images/","signatures/","documents/","healthReports/").contains(dir)){
            return ossService.generateSignature(dir, 5);
        }else{
            throw new JoymartBusinessException("请传入指定目录参数");
        }

    }


    private String generateUniqueFileName(String originalFileName) {
        // 获取原始文件名
        if (!StringUtils.hasText(originalFileName)) {
           throw new JoymartBusinessException("File name is empty");
        }
        // 提取文件扩展名（假设扩展名包含在最后一个 "." 后面）
        String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
        // 生成 UUID
        String uuid = UUID.randomUUID().toString();
        // 拼接新的文件名
        return uuid + extension;
    }
}
